//
//  ScenicPlayVC.m
//  ImGuider
//
//  Created by llt on 2017/4/19.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "ScenicPlayVC.h"
#import "ScenicPlayCCell.h"
#import "MyPlayProgressView.h"
#import "ZFPhoneTransition.h"
#import "PaymentPageVC.h"
#import "PlayBar.h"
#import "SDCycleScrollView.h"
#import "StarRateView.h"
#import "GuiderDetailVC.h"
#import "GuiderDetailVC.h"
#import "GuiderIconView.h"
#import "TagView.h"
#import "CBAutoScrollLabel.h"
#import "BigPicVC.h"
#import "NumberSearchVC.h"
#import "JMHoledView.h"
#import "RecordListDAO.h"
@interface ScenicPlayVC () <UICollectionViewDelegate, UICollectionViewDataSource, UIViewControllerTransitioningDelegate,playBarDelegate,PaymentPageVCDelegate,LoginVCDelegate,SDCycleScrollViewDelegate,NumberSearchVCDelegate>

@property (weak, nonatomic) IBOutlet UIView *BgView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UIView *guiderView;

@property (weak, nonatomic) IBOutlet GuiderIconView *guiderHeaderView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *guiderViewWidth;

@property (weak, nonatomic) IBOutlet UILabel *guiderNameLabel;

//@property (weak, nonatomic) IBOutlet UIButton *mapBtn;

@property (weak, nonatomic) IBOutlet UIView *payView;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet StarRateView *starView;

@property (weak, nonatomic) IBOutlet UILabel *visitLabel;

@property (weak, nonatomic) IBOutlet UILabel *scenicPointNumLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *guiViewWidth;

@property (weak, nonatomic) IBOutlet UIButton *guiderBtn;

@property (weak, nonatomic) IBOutlet UILabel *listenNumLabel;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet TagView *tagView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagViewWidth;

@property (weak, nonatomic) IBOutlet UIButton *buyBtn;

@property (weak, nonatomic) IBOutlet UIButton *searchBtn;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottomSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BgViewHeight;


@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong)PlayBar * playBar;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonnull, strong) MyPlayProgressView * progressBar;

@property (nonatomic, strong)NSIndexPath * currenIndexPath;
@property (nonatomic) NSInteger currentIndex;
@property (nonatomic)BOOL isPlay;

@property (nonatomic)BOOL isInView;// 为了改点的太快 出去播放的bug

@property (nonatomic)BOOL isDownload;

@property (nonatomic) BOOL isSuspend;

@end

@implementation ScenicPlayVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeState:) name:kDownloadCompleteDownNotif object:nil];
    
    if (ISiPhoneX) {
        self.toBottomSpace.constant = 102;
        self.BgViewHeight.constant = SCREEN_WIDTH /4 *5;
    }else{
        self.BgViewHeight.constant = SCREEN_WIDTH;
    }
   // self.mapBtn.hidden = YES;
    self.searchBtn.hidden = YES;
    self.payView.hidden = YES;
    [self.searchBtn setTitle:MYLocalizedString(@"SITEPLAY_SEARCH", nil) forState:UIControlStateNormal];
    self.barBGAlpha = 0.f;
    self.view.backgroundColor = kBGColor;
    self.lastDismissPoint = CGPointMake([UIScreen mainScreen].bounds.size.width - 50, [UIScreen mainScreen].bounds.size.height - 90);
    self.scenicPointNumLabel.textColor = kContentColor;
    self.listenNumLabel.textColor = kContentColor;
    self.timeLabel.textColor = kContentColor;
    self.guiderView.layer.cornerRadius = 22.5f;
    self.guiderView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    self.tagView.tagViewWidth = self.tagViewWidth;
    self.tagView.hidden = YES;
    [self.buyBtn setTitle:MYLocalizedString(@"SITEPLAY_BUY", nil) forState:UIControlStateNormal];
    [self setupCollectionView];
    [self setNavGradient];
    [self createPlayBar];
    [self initScenicFunctionItemView];
    [self loadDataSourceWithAlert:self.alert];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [MobClick event:@"7_1_1"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.isInView = YES;
    [MobClick beginLogPageView:@"7"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     self.isInView = NO;
    [AppManager sharedManager].currentPointID = self.CurrentPointID;
    [MobClick endLogPageView:@"7"];
    if (!self.isStraightPlay){
        
         [[IGAvPlayerManager shareManeger] stop];
    }

}


- (void)changeState:(NSNotification *)notif {
    
    if (self.isSuspend) {
        return;
    }
    

    dispatch_async(dispatch_get_main_queue(), ^ {
        
        NSString *lineID = notif.userInfo[kDownloadNotifLineID];
        
        if (![lineID isEqualToString:self.lineModel.unionid]) {
            return;
        }
        
        CGFloat progress;
        DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
        
        self.lineModel.progress = progress;
        self.lineModel.state = state;
        
        self.playBar.downloadState = state;
        self.playBar.downloadProgress = progress;
        [self.collectionView reloadData];
    });
}

- (IBAction)searchBtnClicked:(UIButton *)sender {
    
    NumberSearchVC * searchVC = [[NumberSearchVC alloc] init];
    
    searchVC.ScenicPointsArray = self.dataSource;
    searchVC.delegate = self;
    BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:searchVC];
    self.isStraightPlay = YES;
    [self presentViewController:nav animated:YES completion:nil];
}


//- (IBAction)changeMap:(UIButton *)sender {
//
//    if (!sender.selected) {
//        self.cycleScrollView.imageURLStringsGroup = self.lineModel.mapPicArray;
//        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
//        self.cycleScrollView.autoScroll = NO;
//        sender.selected = YES;
//    }else {
//        ScenicPoint * scenicPoint = self.dataSource[self.currentIndex];
//         self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
//        self.cycleScrollView.imageURLStringsGroup = scenicPoint.pictureArray;
//        if (scenicPoint.pictureArray.count > 1) {
//            self.cycleScrollView.autoScroll = YES;
//        }else {
//            self.cycleScrollView.autoScroll = NO;
//        }
//
//        sender.selected = NO;
//    }
//}

- (void)changeMapMode:(UIButton *)sender {
    
    if (!sender.selected) {
        self.cycleScrollView.imageURLStringsGroup = self.lineModel.mapPicArray;
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
        self.cycleScrollView.autoScroll = NO;
        [sender setTitle:MYLocalizedString(@"SITEPLAY_PICTURE", nil) forState:UIControlStateNormal];
        sender.selected = YES;
    }else {
        ScenicPoint * scenicPoint = self.dataSource[self.currentIndex];
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        self.cycleScrollView.imageURLStringsGroup = scenicPoint.pictureArray;
        if (scenicPoint.pictureArray.count > 1) {
            self.cycleScrollView.autoScroll = YES;
        }else {
            self.cycleScrollView.autoScroll = NO;
        }
        [sender setTitle:MYLocalizedString(@"SITEPLAY_MAP", nil) forState:UIControlStateNormal];
        sender.selected = NO;
    }
}

- (IBAction)payBtnClicked:(UIButton *)sender {
    
    [MobClick event:@"7_1_2"];
    
    if (![UserManager sharedManager].token) {
        [self goLogin];
        return;
    }
    
    PaymentPageVC * paymentVC = [[PaymentPageVC alloc] init];
    paymentVC.lineModel = self.lineModel;
    paymentVC.delegate = self;
    BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:paymentVC];
    
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)selectSenicPoint:(ScenicPoint *)point {
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[self.dataSource  indexOfObject:point] inSection:0];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (self.lineModel.bought && self.isInView) {
            
            [self selectCellWith:_collectionView ScenicPoint:point IndexPath:indexPath Immediately:YES];
        }else {
            
            self.cycleScrollView.imageURLStringsGroup = point.pictureArray;
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        }
    });
}
- (void)loadDataSourceWithAlert:(BOOL)alert {
    
    if (self.pageType == 1) {
        
        self.isDownload = YES;
        [self setupDatabaseData];
        return;
    }
    
    if (self.pageType == 2) {
        
        [self setupDatabaseData];
    
        if (alert) {
            self.lineModel.inroom = YES;
            if (self.lineModel.inroom) {
                
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.lineModel.unionid];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:MYLocalizedString(@"SITEPLAY_AUTO_DOWNLOAD", nil) cancelButtonTitle:nil commitBtn:MYLocalizedString(@"PUBLIC_OK", nil) commit:nil cancel:nil];
                    
                    [self downloadStart];
                });
                
            } else {
                
                [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:MYLocalizedString(@"PUBLIC_DOWNLOAD_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_COMMIT", nil) commit:^{
                    [self downloadStart];
                } cancel:nil];
            }
        }
        return;
    }
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:kBGColor];
    
    @weakify(self);
    [NetAPIManager getLineDetailWithLinID:[AppManager sharedManager].lineid block:^(LineModel *model, NSError *error) {
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.lineModel = model;
        [self setupDatabaseData];
        
        if (alert) {
            [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_DOWNLOAD_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_COMMIT", nil) commit:^{
                [self downloadStart];
            } cancel:nil];
        }
    }];
}


- (void)setupDatabaseData {
    
    __block LineModel *lineModel = nil;
    
    [DownloadListDAO getLineModelWithUnionid:self.lineModel.unionid Block:^(LineModel *responseModel) {
        
        lineModel = responseModel;
    }];
    
    if (lineModel && lineModel.state != DownloadStateSuspened ) {
        self.isDownload = YES;
        
        self.lineModel.isUpdate = ![self.lineModel.lineid isEqualToString:lineModel.lineid];
        self.lineModel.progress = lineModel.progress;
        
        CGFloat progress;
        DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
        
        self.lineModel.progress = progress;
        self.lineModel.state = state;
        
        self.playBar.downloadState = state;
        self.playBar.downloadProgress = progress;
        
    }
    [self setupData];
}

- (void)UIConfig{
    
    if (self.lineModel.bought) {
   
        self.tagView.hidden = YES;
        
        if (self.lineModel.cansearch) {
            self.searchBtn.hidden = NO;
        }
    }else {
        
        if (self.lineModel.cansearch) {
            self.searchBtn.hidden = NO;
            self.tagView.hidden = YES;
        }else{
            self.tagView.hidden = NO;
        }
    }
    
    if (self.lineModel.hasmap) {
        self.changeMapBtn.hidden = NO;
    }

    if (self.lineModel.hasscore.integerValue > 0) {
        [self.commentBtn setTitle:MYLocalizedString(@"SITEPLAY_USER_COMMENT_BTN", nil) forState:UIControlStateNormal];
    }
    
}

- (void)setupData {
    
    [self UIConfig];
    
    self.priceLabel.text = self.lineModel.price;
    [self.starView setScore:self.lineModel.score.floatValue/10];
    self.visitLabel.text = [NSString localizedStringWithFormat:MYLocalizedString(@"SITEPLAY_TOTAL_BUY", nil),self.lineModel.visits];
    
    self.guiderHeaderView.headerImageName = self.lineModel.guide.headimg;
    
    if (self.lineModel.visits) {
        self.listenNumLabel.text =[NSString stringWithFormat:@"%@",self.lineModel.visits];
    }
    
    self.guiderHeaderView.vip = self.lineModel.guide.vip;
    
    self.guiderNameLabel.text = self.lineModel.guide.realname;
    if (self.lineModel.guide.realname.length <= 6) {
        self.guiderViewWidth.constant = self.lineModel.guide.realname.length * 13.5 + 61;
    }else {
        self.guiderViewWidth.constant = 140;
    }
    self.tagView.tagsArray = self.lineModel.tagArray;
    //self.title= self.lineModel.linename;
    if (self.lineModel.records.count > 0) {
        
        self.dataSource = [NSMutableArray arrayWithArray:self.lineModel.records];
        
        self.scenicPointNumLabel.text = self.lineModel.recordcount;//[NSString stringWithFormat:@"%ld",self.dataSource.count];
    }
    
    if (self.lineModel.timelabel) {
        self.timeLabel.text = [NSString stringWithFormat:@"%@min",self.lineModel.timelabel];
    }
    
    [self initSelectedCell];
    [self.collectionView reloadData];
    
}

- (void)initSelectedCell {
    
    ScenicPoint *model;
    NSIndexPath * indexPath;
    if ( self.dataSource.count > 0 && !self.CurrentPointID) {
        
        model = self.dataSource[0];
        indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        self.currenIndexPath = indexPath;
        
        [self.playBar playMusicWithPlayPath:model withIsPlay:NO];

    } else {
        if ( [[AppManager sharedManager].lineid isEqualToString:self.lineModel.lineid]) {
            
            self.CurrentPointID = [AppManager sharedManager].currentPointID;
            for (int i = 0; i< self.dataSource.count; i++) {
                model = self.dataSource[i];
                
                if ([self.CurrentPointID isEqualToString:model.ID]) {
                    
                    indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    self.currenIndexPath = indexPath;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
                    });
                    break;
                }
            }
        }
        
        
    }
    
    self.currentIndex = indexPath.row;
    self.CurrentPlayIcon = model.pictureArray[0];
    self.cycleScrollView.imageURLStringsGroup = model.pictureArray;
    
}
- (IBAction)goGuiderDetailVC:(UIButton *)sender {
    
    [MobClick event:@"7_1_4"];
    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    for (UIViewController *vc in marr) {
        if ([vc isKindOfClass:[GuiderDetailVC class]]) {
            [marr removeObject:vc];
            break;
        }
    }
    self.navigationController.viewControllers = marr;
    
    GuiderDetailVC * detailVC = [[GuiderDetailVC alloc] init];
    
    detailVC.guiderID = self.lineModel.guideid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


//-(void) configScenicPointNumLableWith:(NSInteger )count {
//
//    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%ld个讲解点",self.lineModel.records.count]];
//
//    // 设置字体和设置字体的范围
//    [string addAttribute:NSFontAttributeName
//                   value:Font(18.0f)
//                    range:NSMakeRange(0, string.length - 4)];
//    // 添加文字颜色
//    [string addAttribute:NSForegroundColorAttributeName
//                    value:kThemeColor
//                    range:NSMakeRange(0, string.length - 4)];
//
//    self.scenicPointNumLabel.attributedText = string;
//}

- (void)setupCollectionView {
    
    CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
    if (ISiPhoneX) {
        frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH /4 *5);
    }
    // 网络加载 --- 创建带标题的图片轮播器
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:frame delegate:nil placeholderImage:[UIImage imageNamed:@"placeholder_squ"]];
    [self.BgView insertSubview:self.cycleScrollView belowSubview:self.guiderView];
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.currentPageDotColor = kThemeColor; // 自定义分页控件小圆标颜色
    self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ScenicPlayCCell" bundle:nil] forCellWithReuseIdentifier:@"ScenicPlayCCell"];
    
    UICollectionViewFlowLayout *flayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat imageHeight = SCREEN_HEIGHT < 568 ? SCREEN_WIDTH * 3 / 4.0f : SCREEN_WIDTH;
    if (ISiPhoneX) {
        imageHeight = SCREEN_WIDTH /4 *5;
    }
    
    CGFloat height = SCREEN_HEIGHT  - 60 - imageHeight - self.toBottomSpace.constant;
    flayout.itemSize = CGSizeMake(height - 25, height);
    flayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    [self.collectionView setCollectionViewLayout:flayout animated:YES];
}


- (void)createPlayBar {
    
    if (!self.playBar) {
        
        self.playBar = [PlayBar shareManeger];
        self.playBar.delegate = self;
        self.playBar.type = 2;
        [self.view insertSubview:self.playBar belowSubview:self.payView];
        
        [self.playBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(8.0);
            make.leading.equalTo(self.view.mas_leading);
            make.trailing.equalTo(self.view.mas_trailing);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(60);
        }];
    }
    
    self.playBar.downloadState = DownloadStateNone;
}
//- (void)setupNavBar {
//
//    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:0];
//
//    UIBarButtonItem *  backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked:)];
//    self.navigationItem.leftBarButtonItem = backItem;
//
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more"] style:UIBarButtonItemStylePlain target:self action:@selector(showMoreMennu)];
//
//    self.navigationItem.rightBarButtonItem = item;
//}

- (void)downloadStart {
    
    [MobClick event:@"7_0_8"];
    
    if (![UserManager sharedManager].token) {
        
        [self goLogin];
        return;
    }
    
    self.isSuspend = NO;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        BOOL hasDownload = [[NSUserDefaults standardUserDefaults] boolForKey:self.lineModel.unionid];
        
        if (!hasDownload) {
            dispatch_async(dispatch_get_main_queue(), ^ {
                [IGUtils showToast:MYLocalizedString(@"SITEPLAY_DOWNLOADTIP", nil)];
            });
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.lineModel.unionid];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
    });
    
    self.isDownload = YES;
    CGFloat progress;
    DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
    
    if (state == DownloadStateCompleted || state == DownloadStateFailed) {
        self.lineModel.state = state;
    }
    
    self.lineModel.progress = progress;
    self.lineModel.state = self.lineModel.state;
    
    self.playBar.downloadState= self.lineModel.state;
    self.playBar.downloadProgress = progress;
    
    [[DownloadManager sharedManager] addDownloadWithLineModel:self.lineModel];
    [self.collectionView reloadData];
}

- (void)downloadSuspend {
    
    [[DownloadManager sharedManager] pauseWithLineModel:self.lineModel];
    self.isSuspend = YES;
    self.isDownload = NO;
    [self.collectionView reloadData];
}
//-(void)downloadSuspend {
//
//    [[DownloadManager sharedManager] deleteDownloadWithLineModel:self.lineModel];
//    [DownloadListDAO getLineModelWithUnionid:self.lineModel.unionid Block:^(LineModel *lineModel) {
//
//        if (lineModel) {
//            self.isDownload = YES;
//            self.playBar.downloadBtn.state = lineModel.state;
//            self.playBar.downloadBtn.progress = lineModel.progress;
//            self.lineModel.state = lineModel.state;
//            self.lineModel.isUpdate = ![self.lineModel.lineid isEqualToString:lineModel.lineid];
//            self.lineModel.progress = lineModel.progress;
//        }else {
//            self.isDownload = NO;
//            self.playBar.downloadBtn.state = DownloadStateNone;
//        }
//
//        [self.collectionView reloadData];
//    }];
//}


- (void)loginSuccessCallback {
    [self loadDataSourceWithAlert:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - playBarDelegate

- (void)changeRecordPointWith:(NSInteger)state isAutomatic:(BOOL)isAutomatic {
    
    NSInteger index = self.currentIndex + state;
    NSInteger totalCount = self.dataSource.count;
    
    
    if (index >= totalCount) {
       
        if (!isAutomatic) {
            
            [IGUtils showToast:MYLocalizedString(@"SITEPLAY_LAST_ONE", nil)];
        }
        return;
    }
    
    if (index < 0 ) {
        [IGUtils showToast:MYLocalizedString(@"SITEPLAY_FIRST_ONE", nil)];
        return;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex + state inSection:0];
    
    ScenicPoint * model = self.dataSource[_currentIndex + state];
    
    [self selectCellWith:self.collectionView ScenicPoint:model IndexPath:indexPath Immediately:YES];
    
}


#pragma mark-UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ScenicPlayCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ScenicPlayCCell" forIndexPath:indexPath];
    
    if (self.isDownload) {
        cell.showProgress = YES;
    } else {
        cell.showProgress = NO;
    }
    
    ScenicPoint * scenicPoint = self.dataSource[indexPath.row];
    [cell configDataWith:scenicPoint];
    
    if (indexPath.row == 0  && !self.lineModel.bought) {
        cell.playBtn.hidden = NO;
    }
    cell.select = NO;
    
    if (self.currenIndexPath.row == indexPath.row  && self.lineModel.bought) {
        
        cell.select = YES;
        cell.record = NO;
    }
    
    return cell;
}

- (void)selectCellWith:(UICollectionView *)collectionView ScenicPoint:(ScenicPoint *)model  IndexPath:(NSIndexPath *)indexPath Immediately:(BOOL)isImmediately {
    
    
    if (self.currenIndexPath) {
        ScenicPlayCCell * cell = (ScenicPlayCCell *)[collectionView cellForItemAtIndexPath:self.currenIndexPath];
        cell.select = NO;
    }
    ScenicPlayCCell * currenCell = (ScenicPlayCCell *)[collectionView cellForItemAtIndexPath:indexPath];
    currenCell.select = YES;
    if (model.spotpictures && !self.changeMapBtn.selected) {
        
        
        self.cycleScrollView.imageURLStringsGroup = model.pictureArray;
        
    }else  if(model.map.length > 0){
        
        [self.cycleScrollView selectToIndex:[self.lineModel.mapPicArray indexOfObject:model.map]];
    }
    
    
    IGLog(@"%@",model.playpath);
    [self.playBar playMusicWithPlayPath:model withIsPlay:isImmediately];
    
    [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [self.collectionView reloadData];
    self.currenIndexPath = indexPath;
    self.currentIndex = indexPath.row;
    self.CurrentPointID = model.ID;
    self.CurrentPlayIcon = model.pictureArray[0];
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.currenIndexPath == indexPath || (!self.lineModel.bought && indexPath.row == 0)) {
        return;
    }
    if (self.lineModel.bought) {
        
        ScenicPoint * scenicPoint = self.dataSource[indexPath.row];
        if (scenicPoint.canplay && scenicPoint.playpath.length > 0) {
            
            [self selectCellWith:collectionView ScenicPoint:scenicPoint  IndexPath:indexPath Immediately:YES];
        }
        [MobClick event:@"7_0_3"];
    } else {
        [MobClick event:@"7_1_3"];
        
        if (![UserManager sharedManager].token) {
            [self goLogin];
            return;
        }
        
        PaymentPageVC * paymentVC = [[PaymentPageVC alloc] init];
        paymentVC.lineModel = self.lineModel;
        paymentVC.delegate = self;
        BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:paymentVC];
        
        [self presentViewController:nav animated:YES completion:nil];
        
    }
}

- (void)paySuccessCallback {
    [self loadDataSourceWithAlert:YES];
}
#pragma mark-UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(8, 8, 8, 8);//分别为上、左、下、右
}


#pragma mark-SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    if (!self.changeMapBtn.selected) {
        return;
    }
    
    if (self.lineModel.mapPicArray.count > 0) {
        
        BigPicVC * vc = [[BigPicVC alloc] initWithIndex:0];
        vc.imageArray = self.lineModel.mapPicArray;
        self.isStraightPlay = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}





/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
